﻿namespace Summoner
{
    using System.Collections.Generic;
    using System.IO;
    using UnityEditor;
    public class BundleFunction
    {
        /// <summary>
        /// Clear AssetBundles
        /// </summary>
        private static void ClearBundles()
        {
            if (Directory.Exists(AssetPath.PublishPath))
            {
                Directory.Delete(AssetPath.PublishPath, true);
            }
            Directory.CreateDirectory(AssetPath.PublishPath);
        }

        /// <summary>
        /// specificial process the build list
        /// </summary>
        /// <param name="assetinfo"></param>
        /// <param name="level"></param>
        /// <param name="buildtarget"></param>
        public static void GenerateAssetBundle(List<AssetInfo> assetlist, BuildTarget buildtarget)
        {
            ClearBundles();
            List<AssetBundleBuild> bundletaskList = new List<AssetBundleBuild>();
            foreach (AssetInfo info in assetlist)
            {
                if(info.type == "UnityEngine.MovieTexture")
                {
                    ProcessCopy(info);
                }
                else
                {
                    bundletaskList.Add(new AssetBundleBuild() { assetNames = new string[] { info.pathInEditor }, assetBundleName = info.assetName.ToLower() + ".unity3d" });
                }
            }
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            BuildPipeline.BuildAssetBundles(AssetPath.PublishPath, bundletaskList.ToArray(), BuildAssetBundleOptions.None, buildtarget);
            AssetDatabase.Refresh();
        }

        private static void ProcessCopy(AssetInfo info)
        {
            if(!Directory.Exists(AssetPath.PublishPath))
            {
                Directory.CreateDirectory(AssetPath.PublishPath);
            }
            File.Copy(info.pathInEditor, Path.Combine(AssetPath.PublishPath, Path.GetFileName(info.pathInEditor)), true);
        }
    }
}